<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useCurrentUserStore } from '../stores/currentUserStores'
import { securityApi } from '../api'
import { ElNotification } from 'element-plus'

// 初始化 user 为一个空的 User 对象
const username = ref('')
const password = ref('')
const router = useRouter()
const userStore = useCurrentUserStore()

const login = async () => {
  try {
    const response = await securityApi.login(username.value,password.value)
    if (response.data && response.data.Authorization) {
      userStore.setToken(response.data.Authorization)
      securityApi.userInfo().then(res => {
        userStore.setUser(res.data)
        router.push('/admin') // 登录成功后跳转到仪表板页面
      })
    } else {
      ElNotification({
        title: '登录失败',
        type: 'error',
        message: '无效的响应数据',
      })
    }
  } catch (err) {
    console.error('登录错误', err)
    ElNotification({
      title: '登录失败',
      type: 'error',
      message: '请检查您的用户名和密码',
    })
  }
}
</script>

<template>
  <div class="login">
    <div class="background"></div>
    <div class="form bg-white rounded p-10 text-center shadow-md">
      <h1 class="text-3xl">泡泡站</h1>
      <p class="text-sm text-gray-700">鱼泡泡的精彩瞬间</p>
      <div class="my-4 text-left">
        <label for="email" class="text-gray-900">Username:</label>
        <input type="text" class="border block w-full p-2 mt-2 rounded" v-model="username" placeholder="Enter Username">
      </div>

      <div class="my-4 text-left">
        <label for="email" class="text-gray-900">Password:</label>
        <input type="password" class="border block w-full p-2 mt-2 rounded" v-model="password" placeholder="Enter Password">
      </div>

      <button class="bg-black text-white py-2 mt-4 inline-block w-full rounded" @click="login">
        Login
      </button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}
.form{
  width: 420px;
  h1{
    color: #0a0a0a;
  }
}

.background {
  background: url('@/assets/images/login_background.png');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: bottom center;  
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  z-index: -1;
  filter: blur(5px);
}
</style>